package com.asl.website.sysAboutContact.service.impl;

import com.asl.website.sysAboutContact.domain.SysAboutContact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;


/**
 * @author 482944566@qq.com
 * @version 1.0
 * @date 2025-05-25
 */
@Service
public class EmailService {
    private final JavaMailSender mailSender;
    @Value("${asl.email.fromEmail}")
    private String fromEmail;
    @Value("${asl.email.toEmail}")
    private String toEmail;
    @Value("${asl.email.subjectTitle}")
    private String subjectTitle;
    @Autowired
    public EmailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendContactEmail(SysAboutContact contact) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置发件人（必须符合 RFC5322 格式）
            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject(subjectTitle);
            // 使用数据库设置的时间（已在插入操作时设置）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTimeStr = contact.getCreateTime() != null ?
                    sdf.format(contact.getCreateTime()) : "无时间信息";
            // 构建邮件正文（包含所有字段）
            String emailText = String.format(
                    "新提交的联系信息：\n" +
                            "称呼：%s\n" +
                            "职务：%s\n" +
                            "姓：%s\n" +
                            "名：%s\n" +
                            "公司名称：%s\n" +
                            "邮箱地址：%s\n" +
                            "主题：%s\n" +
                            "联系电话：%s\n" +
                            "信息内容：%s\n" +
                            "时间：%s\n",
                    contact.getSalutation(),
                    contact.getJobTitle(),
                    contact.getLastName(),
                    contact.getFirstName(),
                    contact.getCompanyName() != null ? contact.getCompanyName() : "无",
                    contact.getEmail(),
                    contact.getPhone() != null ? contact.getPhone() : "未提供",
                    contact.getSubject() != null ? contact.getSubject() : "无",
                    contact.getMessage() != null ? contact.getMessage() : "无",
                    createTimeStr
            );
            helper.setText(emailText);
            mailSender.send(message);
        } catch (MessagingException e) {
            System.out.println("邮件发送失败，数据ID："+contact.getId()+e);
        }
    }
}
